
define([
    'jquery',
    'nav',
    'carOperate',
    'validateLogin'
], function (a, nav, carOperate, user) {
    'use strict';

    function Car(a) {
        this.a = a;
        this.data = "";
        this.storage = "";
        this.total = 0;
        this.count = 0;
        this.reduce = 10;
        this.carOperate = new carOperate();

    }
    $.extend(Car.prototype, {
        init: function () {
            this.data = this.carOperate.queryProduct("list");
            this.getCookie();
            this.renderStore();
            setTimeout(() => {
                this.bindEvent();
            }, 500);
        },
        getCookie: function () {
            if (user !== '') {
                this.storage = this.carOperate.getStorage();
            }

        },
        bindEvent: function () {
            $("#btnSelAll").on("click", $.proxy(this.selAllProduct, this));
            nav(".describle-head-right", ".list ul input", this.selProduct.bind(this));
            nav(".describle-head-right", "#btnAdd", this.addProduct.bind(this));
            nav(".describle-head-right", "#btnReduce", this.subProduct.bind(this));
            nav(".describle-head-right", "#btnDel", this.removeProduct.bind(this));
            nav(".describle-head-right", ".list shop-head input", $.proxy(this.selAllStoreOfProduct, this));
        },
        selAllProduct: function () {

        },
        selAllStoreOfProduct: function (item) {
            if (!this.storage) return false;
            var stores = $(item).parents("li").siblings().find("input");
            // console.log(stores)

        },
        selProduct: function (item) {
            var data_id = $(item).parents("li").attr("data-id");
            var cat_id = $(item).parents("li").attr("data-catId");
            var chked = $(item).attr("checked");
            var chk = (typeof chked == "undefined") ? "true" : "false";
            // console.log(chk,typeof chked=="undefined")
            var ret = this.carOperate.selProduct(cat_id + "", data_id + "", chk);
            this.storage = ret.data;
            if (chk === "true") {
                $(item).removeAttr("unchecked");
                $(item).attr("checked", "checked");
                $(item).attr("data-type", "right");
            }
            else {
                $(item).removeAttr("checked");
                $(item).attr("unchecked", "unchecked");
            }

            this.selAllStoreOfProduct(item);
        },

        queryCurrent(goods_id) {
            var current = "";
            var find = this.data.some((item) => {

                if (item.goods_id == goods_id)
                    return current = item;
            })
            return current;
        },
        renderStore: function () {
            console.log(this.storage, JSON.stringify(this.storage), JSON.stringify(this.storage) == "{}")
            if (!this.storage || (JSON.stringify(this.storage) == "{}") || !this.data || !user) {
                $(".cart-empty").css({
                    display: "block"
                })
                $(".list").html('');
                return false;
            }
            console.log(111)
            this.total = 0;
            this.count = 0;
            var html = "";
            var childHtml = "";
            $(".cart-empty").css({
                display: "none"
            })
            $.each(this.storage, (function (key, item) {
                childHtml = this.renderProduct(item);
                html +=
                    `
                     
                <div class="store">
                    <div class="shop-head" data-id=${key}>
                        <input type="checkbox" id="rBtn" class="selAll">
                        <span><i></i> 扩店促销</span>
                        <a href="###">已享满98元减10,去凑单</a>
                        <ul>
                             ${childHtml}
                        </ul>
                    </div>
                </div>
                `
            }).bind(this));
            var totalHtml = this.renderTotal(this);

            html += totalHtml;
            $(".list").html(html);
            return childHtml.count;
        },
        renderProduct: function (item) {
            var html = "";
            var code = "M";
            var color = "黑色";
            $.each(item, (function (key, product) {
                var obj = this.queryCurrent.call(this, product.goods_id);

                if (obj == "") return false;
                console.log(product.goods_isSel ? "checked=checked" : "unchecked=unchecked", product.goods_isSel)
                html += `
            <li data-id="${obj.goods_id}" data-catId=${obj.cat_id1} data-price="${obj.normal_price}">
                <a href="./detail.html?${obj.goods_id}" class="img-link">
                    <input type="checkbox" id="rBtn" class="chk" ${product.goods_isSel == "true" ? "checked=checked" : "unchecked=unchecked"}>
                    <img src="${obj.hd_thumb_url}" alt="">
                    <div class="img-right">
                        <span class="title">${obj.short_name}</span>
                        <div class="productPrice">
                            <span class="productPrice_now">${code}</span>
                            <strong class="productPrice_old">${color}</strong>
                        </div>
                    </div>
                </a>
                <div class="second">
                <span class="productPrice_now">￥${(obj.normal_price) / 100} &nbsp;/&nbsp;
                    <strong class="productPrice_old">￥${(obj.market_price) / 100}</strong>
                </span>
                </div>
                <div class="third">
                    <div class="marginLeft">
                        <i class="plus" id="btnReduce">-</i>
                        <span class="plus num">${product.goods_count}</span>
                        <i class="plus" id="btnAdd">+</i>
                    </div>
                </div>
                <div class="fourth">
                    <span class="price subTotal">￥${(product.goods_price * product.goods_count) / 100}</span>
                </div>
                <div class="fifth">
                    <i class="iconfont icon_white" id="btnDel">&#xe601;</i>
                </div>
            </li>
            `
                this.total += (obj.normal_price * product.goods_count) / 100;
                this.count++;
            }).bind(this));
            return html;
        },
        renderTotal: function () {
            if (!this.data || user == '') return false;
            var html = "";
            html +=
                `<div class="shop-footer">
                    <input type="checkbox" id="btnSelAll" class="selAll" value="">全选
                        <div class="total">
                            <span>已选择 ${this.count} 件，总额：￥${this.total} 满减：￥${this.reduce}， 合计（不含运费）</span>
                            <strong href="###" class="price">￥${(this.total - this.reduce).toFixed(2)}</strong>
                            <span class="car">去结算</span>
                        </div>
                 </div>`
            return html;
        },
        addProduct: function (item) {
            // var txt = $(item).siblings("span");
            // var btnReduce = $(item).siblings("i");
            var data_id = $(item).parents("li").attr("data-id");
            var cat_id = $(item).parents("li").attr("data-catId");
            var price = $(item).parents("li").attr("data-price");
            // var num = parseInt(txt.html());
            var res = this.carOperate.addProduct(cat_id + "", data_id + "", 1, price);
            this.storage = res.data;
            this.changeCount(item, res.item);
            // txt.html(num + 1);
            // if (txt.html() == "1") {
            //     btnReduce.removeAttr("disabled");
            // }
        },
        subProduct: function (item) {
            var txt = $(item).siblings("span");
            var num = parseInt(txt.html());
            if (num == 1) return false;
            // var btnReduce = $(item).siblings("i");
            var data_id = $(item).parents("li").attr("data-id");
            var cat_id = $(item).parents("li").attr("data-catId");
            var ret = this.carOperate.reduceProduct(cat_id + "", data_id + "", 1);
            // console.log(ret)
            this.storage = ret.data;
            this.changeCount(item, ret.item);
            // txt.html(num - 1);
            // if (txt.html() == "1") {
            //     btnReduce.attr("disabled");
            // }
        },
        removeProduct: function (item) {
            // console.log($(item).parents("li").attr("data-catId"))
            var data_id = $(item).parents("li").attr("data-id") + "";
            var cat_id = $(item).parents("li").attr("data-catId") + "";
            this.storage = this.carOperate.removeProduct(cat_id, data_id);
            this.renderStore();
            
        },
        selAllProduct: function (item) {

        },
        changeCount: function (item, data) {
            // console.log(data)
            var txt = $(item).siblings("span");
            var subTotal = $(item).parents("li").find(".subTotal");
            var btnReduce = $(item).siblings("i");
            txt.html(data.goods_count);
            subTotal.html(data.goods_count * data.goods_price / 100)
            if (data.goods_count == "1") {
                btnReduce.attr("disabled");
            }
        }
    })

    return Car;

});